/**
 ** @author:   郭一甲
 ** @date:     2019.2.23
 ** @brief:    封装linux定时器
 */

#include "timer.h"

struct timer_arg
{
	struct timeval delay;
	void (*fun)(void);
};

static void *timer_fun(void *arg)
{
	long delay = 0;
	struct timer_arg *t_arg = (struct timer_arg *)arg;
	
	//计算出延时时间
	delay = (t_arg->delay.tv_sec*(1000000)) + (t_arg->delay.tv_usec);
	
	//进行延时
	usleep(delay);
	
	//延时时间到了以后执行超时函数
	(t_arg->fun)();
	
	//完成后释放资源
	free(arg);
	arg = NULL;
}

/**
 * 定时器函数
 * @param  fun 超时后执行函数]
 * @param  delay 超时时间
 * @return 暂时只返回线程ID，后期优化
 */
int timer(void (*fun)(void), struct timeval delay)
{
	//这里线程不能等待，并且这里栈变量要改为堆变量，否则声明周期结束后会导致混乱。浓咖啡@2019.2.28
	pthread_t id;
	struct timer_arg *arg_tmp = (struct timer_arg *)malloc(sizeof(struct timer_arg));
	
	arg_tmp->delay = delay;
	arg_tmp->fun = fun;
	
	pthread_create(&id, NULL, timer_fun, arg_tmp);
	//pthread_join(id, NULL);
	
	return id;
}

